<template>
  <article class="page page-ocr">
    <h4 class="text-center">OCR图片文字识别</h4>
    <div class="tabs-bar">
      <div v-for="(v, i) in tabsList" :key="i" :class="['tab-item', { active: i === tabActiveIndex }]"
        @click="tabItemClick(i)">{{ v.label }}</div>
    </div>
    <form class="form">
      <fieldset>
        <legend>设置&操作</legend>
        <div class="fieldset-content">
          <div class="form-item row-flex" align="center">
            <div class="row-flex-prefix">识别方式</div>
            <div class="row-flex-main text-left">
              <div class="form-check form-check-inline" v-for="(v, i) in radiosList" :key="i">
                <input class="form-check-input" type="radio" :id="`ocr_${v.value}`" :value="v.value" v-model="radioActive">
                <label class="form-check-label" :for="`ocr_${v.value}`">{{ v.label }}</label>
              </div>
            </div>
          </div>
          <div class="form-item row" v-if="radioActive==='baiduapi'">
            <div class="col col-6">
              <div class="row-flex" align="center">
                <div class="row-flex-prefix">Secret Key</div>
                <div class="row-flex-main">
                  <input class="form-control" type="text" v-model.trim="SecretKey" placeholder="请输入SecretKey" />
                </div>
              </div>
            </div>
            <div class="col col-6">
              <div class="row-flex" align="center">
                <div class="row-flex-prefix">API Key</div>
                <div class="row-flex-main">
                  <input class="form-control" type="text" v-model.trim="APIKey" placeholder="请输入APIKey" />
                </div>
              </div>
            </div>
          </div>
          <div class="form-item row" v-if="radioActive==='baiduapi'">
            <div class="col col-6">
              <div class="row-flex" align="center">
                <div class="row-flex-prefix">AccessToken</div>
                <div class="row-flex-main">
                  <input class="form-control" type="text" v-model.trim="AccessToken" placeholder="根据SecretKey和APIKey获取（每月获取一次即可）" readonly />
                </div>
                <div class="row-flex-suffix"><x-button @click="getAccessToken">获取</x-button></div>
              </div>
            </div>
            <div class="col col-6">
              <div class="row-flex" align="center">
                <div class="row-flex-prefix">帮助文档</div>
                <div class="row-flex-main text-left">
                  <span class="btn btn-link" @click="goBaiduDocment">API Key | Secret Key | AccessToken获取方式</span>
                </div>
              </div>
            </div>
          </div>
          <!-- <div class="form-item row-flex" align="center" v-if="radioActive==='tesseract'">
            <div class="row-flex-prefix">训练数据</div>
            <div class="row-flex-main">
              <input class="form-control" type="text" v-model="dbPath" readonly />
            </div>
            <div class="row-flex-suffix"><x-button @click="setPath">选择...</x-button></div>
          </div> -->
          <component class="tab-content" :is="tabActive.component" :ocrType="radioActive" :AccessToken="AccessToken"></component>
        </div>
      </fieldset>
    </form>
  </article>
</template>

<script>
import cmpDecodeSingle from './decode-single.vue'
// import cmpDecodeBatch from './decode-batch.vue'
const {remote, shell} = global.require('electron')
const {dialog} = remote
const selfWindow= remote.getCurrentWindow()
export default {
  name: 'ocr',
  components: {
    cmpDecodeSingle,
    // cmpDecodeBatch,
  },
  data() {
    return {
      tabActiveIndex: 0,
      tabsList: [
        { label: '单个识别', value: 'decodeSingle', component: 'cmpDecodeSingle' },
        // { label: '批量识别', value: 'decodeBatch', component: 'cmpDecodeBatch' },
      ],
      dbPath: '',
      // 百度在线API
      SecretKey: '',
      APIKey: '',
      AccessToken: '',
      radioActive: 'baiduapi',
      radiosList: [
        { label: '百度在线API', value: 'baiduapi' },
        { label: 'PP飞桨', value: 'paddle' },
        { label: 'Tesseract', value: 'tesseract' },
      ]
    }
  },
  computed: {
    tabActive() {
      return this.tabsList[this.tabActiveIndex] || {}
    }
  },
  mounted() {
    this.getAccessTokenLocal()
  },
  beforeDestroy() {
  },
  methods: {
    tabItemClick(index) {
      this.tabActiveIndex = index
    },
    // 设置文件路径
    setPath () {
      let filePaths = dialog.showOpenDialogSync(selfWindow, {
        title: '选择文件',
        buttonLabel:'确定',
        defaultPath: this.$sharedObject('desktopPath'),
        properties: ['openFile']
      })
      if (filePaths instanceof Array && filePaths.length > 0) {
        this.dbPath = filePaths[0]
      }
    },
    // 获取AccessToken
    getAccessToken () {
      if (!this.APIKey || !this.SecretKey) {
        this.$toast('请输入APIKey和SecretKey后再试')
        return
      }
      fetch(`https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${this.APIKey}&client_secret=${this.SecretKey}`)
      .then((res) => {
        return res.json()
      }).then((data) => {
        console.log(data)
        this.AccessToken = (data || {})['access_token'] || ''
        this.setAccessTokenLocal(this.AccessToken)
      }).catch((err) => {
        console.log(err)
        this.$toast('AccessToken获取失败')
      })
    },
    // 获取本地已存储的AccessToken
    getAccessTokenLocal () {
      let { getVal } = this.$sharedObject('electronSettingsPack')
      getVal('tools-ocr', 'AccessToken').then((value) => {
        this.AccessToken = value || ''
      })
    },
    // 将AccessToken保存到本地
    setAccessTokenLocal (value) {
      let { setVal } = this.$sharedObject('electronSettingsPack')
      setVal('tools-ocr', 'AccessToken', value)
    },
    // 前往百度接口文档
    goBaiduDocment () {
      shell.openExternal('https://ai.baidu.com/ai-doc/REFERENCE/Lkru0zoz4')
    },
  }
}
</script>

<style scoped lang="less">
@import "~@/assets/css/_mixins.less";
@import "~@/assets/css/_color.less";
.form-item {
  margin-bottom: .5em;
  .row-flex-prefix {
    width: 6em;
    text-align: right;
  }
}
.page-ocr {
  display: flex;
  flex-direction: column;
  .tabs-bar {
    margin-bottom: 1em;
  }
  .form {
    height: 0;
    flex-grow: 1;
    fieldset {
      height: 100%;
      .fieldset-content {
        height: calc(100% - 2em);
        display: flex;
        flex-direction: column;
        .tab-content {
          height: 0;
          flex-grow: 1;
          overflow: hidden auto;
        }
      }
    }
  }
}</style>
